package com.fmy.springbootutils.tool;

import com.fmy.springbootutils.unusual.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Properties;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName PropertiesTool.java
 * @Description TODO properties文件工具类
 * @createTime 2019年06月26日 10:29:00
 */
@Slf4j
public class PropertiesTool {

    /**
     * 获取Properties对象
     *
     * @return
     */
    public static Properties getProperties(String configPath) {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(configPath));
            BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            properties.load(bf);
        } catch (FileNotFoundException e) {
            throw new BusinessException(configPath + "文件未找到");
        } catch (IOException e) {
            throw new BusinessException("出现IOException");
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                throw new BusinessException(configPath + "文件流关闭出现异常");
            }
        }
        return properties;
    }

    /**
     * 根据key查询value值
     *
     * @param key key
     * @return
     */
    public static String getValue(String configPath, String key) {
        Properties properties = getProperties(configPath);
        String value = properties.getProperty(key);
        return value;
    }

    /**
     * 新增/修改数据
     *
     * @param key
     * @param value
     */
    public static boolean setValue(String configPath, String key, String value) {
        Properties properties = getProperties(configPath);
        properties.setProperty(key, value);
        //此处获取的路径是target下classes
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(configPath);
            properties.store(fileOutputStream, "注释");
            return true;
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (null != fileOutputStream) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                throw new BusinessException(configPath + "文件流关闭出现异常");
            }
        }
        return false;
    }

}
